//
//  AppDelegate.m
//  LockManagement
//
//  Created by apple on 2018/7/21.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "AppDelegate.h"
#import "GYLoginViewController.h"
#import "GYMainTabBarController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "GYNetWorkTools.h"
#import "GYUploadLog.h"

@interface AppDelegate ()<BMKGeneralDelegate>

/** 地图引擎类 */
@property (nonatomic, strong) BMKMapManager *mapManager;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //0.监听登陆成功消息
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess) name:userLoginSuccess object:nil];
    //监听退出登录成功
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutSuccess) name:userlogoutSuccess object:nil];
    
    //1.监听网络状态
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        self.networkState = status;
        if (status == 1 || status == 2) {
            //代表有网
            NSString *filePath = [NSString CachesDir:@"uploadLog.plist"];
            NSMutableArray *cachesLogArray = [NSMutableArray arrayWithContentsOfFile:filePath];
            NSString *IP = GETOBJ(@"IP")
            NSString *port = GETOBJ(@"port")
            if (cachesLogArray.count != 0) {
                for (NSData *data in cachesLogArray) {
                    GYUploadLog *uploadLog = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                    [GYNetWorkTools requestLogWithURL:[NSString stringWithFormat:@"http://%@:%@/api/log",IP,port] logTime:uploadLog.logTime logType:uploadLog.logType keyID:uploadLog.keyID lockID:uploadLog.lockID logState:uploadLog.logState success:^(NSDictionary *obj) {
                        //NSLog(@"obj=============%@  msg===========%@",obj,[obj objectForKey:@"msg"]);
                        int state = [[obj objectForKey:@"state"] intValue];
                        if (state == 0) {
                            NSLog(@"上传开锁日志成功!");
                            //删除这个数据
                            [cachesLogArray removeObject:data];
                            //写入文件
                            [cachesLogArray writeToFile:filePath atomically:YES];
                        }
                    } error:^(NSError *error) {
                        NSLog(@"error=============%@",error);
                    }];
                }
            }
        }
    }];
    
    [reachabilityManager startMonitoring];
    
    
    //初始化地图
    // 要使用百度地图，请先启动BaiduMapManager
    self.mapManager = [[BMKMapManager alloc]init];
    
    /**
     *百度地图SDK所有接口均支持百度坐标（BD09）和国测局坐标（GCJ02），用此方法设置您使用的坐标类型.
     *默认是BD09（BMK_COORDTYPE_BD09LL）坐标.
     *如果需要使用GCJ02坐标，需要设置CoordinateType为：BMK_COORDTYPE_COMMON.
     */
//    if ([BMKMapManager setCoordinateTypeUsedInBaiduMapSDK:BMK_COORDTYPE_BD09LL]) {
//        NSLog(@"经纬度类型设置成功");
//    } else {
//        NSLog(@"经纬度类型设置失败");
//    }
    BOOL ret = [_mapManager start:@"4MN0PuC8BkaX9LGIA7V4ACkUlDPGGVpu" generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    //1.创建window
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    GYLoginViewController *loginController = [[GYLoginViewController alloc] initWithNibName:@"GYLoginViewController" bundle:nil];
    self.window.rootViewController = loginController;

    [self.window makeKeyAndVisible];
    
    return YES;
}

/**
 用户登录成功
 */
- (void)loginSuccess {
    GYMainTabBarController *main = [[GYMainTabBarController alloc] init];
    self.window.rootViewController = main;
}

/**
 用户退出登录成功
 */
- (void)logoutSuccess {
    GYLoginViewController *loginController = [[GYLoginViewController alloc] initWithNibName:@"GYLoginViewController" bundle:nil];
    self.window.rootViewController = loginController;
}


#pragma mark -- 百度地图 BMKGeneralDelegate

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

@end
